import { useCallback, useState, useEffect, useContext, useMemo } from 'react';
import { InbizImageSearchScreenshot } from 'inbiz-image-search-screenshot';
import { InbizIcon } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import { Checkbox, Select } from 'antd';
import SortArea from '../web/components/RightPanel/SortArea'
import EventContext from './EventContext';
import type { IConfigItem } from '../web/components/content';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import type { ISearchData } from '../../designer/service';
import type { ReactElement } from 'react';

type ISort = (Omit<Exclude<IConfigItem['config']['sortField'], undefined>[number], 'sort'> & {
  selected: boolean;
  sort: 'asc' | 'desc' | any;
})[];

const { Option } = Select
function ContentHead({
  sort,
  showStyle,
  total,
  sortField,
  onSortChange,
  onShowStyleClick,
  children,
  dataSoure,
  config,
  selected,
  onSelect,
  $showRightPanel,
  showRightPanel,
  CenterPlugin,
  showImgSearch,
  params,
  filterNumber,
  categoryLevel,
  controlId
}: {
  total?: number;
  showStyle?: 'thumbnail' | 'list' | 'bigthumbnail';
  sortField: IConfigItem['config']['sortField'];
  sort: { IndexFieldName: string; order: 'asc' | 'desc' | undefined };
  onSortChange: (data: { IndexFieldName: string; order: 'asc' | 'desc' | undefined }) => void;
  onShowStyleClick?: (params: 'list' | 'thumbnail' | 'bigthumbnail') => void;
  children?: (sortList: ISort, sortClick: (params) => void) => ReactElement;
  config: any;
  dataSoure: any;
  selected: ISearchData['RawList'];
  onSelect: (node: ISearchData['RawList'][number], checked: boolean) => void;
  showImgSearch: boolean;
  rightFormRef: any,
  filterNumber: number,
  params: any,
  $showRightPanel: any,
  showRightPanel: any,
  CenterPlugin: any,
  categoryLevel: any,
  controlId: string
}) {
  const { inbiz } = useContext(EventContext);
  const [visible, $visible] = useState(false);
  const [imgDisplay, $imgDisplay] = useState(true)
  const [sortList, $sortList] = useState<ISort>([]);
  const checkedDataArray = (e: CheckboxChangeEvent) => {
    for (let index = 0; index < dataSoure.length; index++) {
      const element = dataSoure[index];
      onSelect(element, e.target.checked);
    }
  };
  useEffect(() => {
    $sortList(
      (sortField || [])
        .filter((item) => item.enable)
        .map((item) => ({
          ...item,
          sort: item.IndexFieldName === sort.IndexFieldName ? sort.order : item.sort || 'desc',
          selected: item.IndexFieldName === sort.IndexFieldName && !!sort.order,
        })),
    );
  }, [sortField, sort]);
  const handleClick = useCallback(
    (IndexFieldName: string) => {
      $sortList((list) => {
        const index = list.findIndex((item) => item.IndexFieldName === IndexFieldName);
        const cur = list[index];
        if (cur.selected) {
          const newList = [...list];
          const nextSort = cur.sort == 'asc' || cur.sort.sort == 'asc' ? 'desc' : 'asc';
          onSortChange?.({ IndexFieldName, order: nextSort });
          if (cur.sort.sort) {
            newList[index] = {
              ...newList[index],
              sort: {
                ...cur,
                sort: nextSort
              },
              selected: true,
            };
          } else {
            newList[index] = {
              ...newList[index],
              sort: nextSort,
              selected: true,
            };
          }

          return newList;
        } else {
          let orderValue = cur.sort || order[0];
          if (typeof orderValue == 'object') {
            orderValue = orderValue.sort
          }
          onSortChange?.({ IndexFieldName, order: orderValue });
          return list.map((item) => ({
            ...item,
            selected: item.IndexFieldName === IndexFieldName,
          }));
        }
      });
    },
    [onSortChange],
  );
  const { isAllChecked, indeterminate } = useMemo(() => {
    const uniqueKey =
      config.uniqueField && config.uniqueField.length > 0
        ? config?.uniqueField?.[0]?.IndexFieldName
        : '_id';
    if (config.checkbox && dataSoure && dataSoure.length > 0) {
      const dataSoureKeys = dataSoure.map((item) => item.RawData[uniqueKey]); // 列表的key
      const selectedKeys = selected.map((item) => item.RawData[uniqueKey]); // 选中的key
      const filterKeys = dataSoureKeys.filter((ele: string | number) => selectedKeys.includes(ele)); // 筛选的key
      const checkedAll = dataSoureKeys.every((ele: string | number) => selectedKeys.includes(ele)); // 筛选的key
      // 如果不是全选或者没有选中项的时候
      if (checkedAll || filterKeys.length == 0) {
        return {
          isAllChecked: checkedAll,
          indeterminate: false,
        };
      }
      // 有选中的但不是全部选中
      return {
        isAllChecked: false,
        indeterminate: true, // 代表半选状态
      };
    } else {
      return {
        isAllChecked: false,
        indeterminate: false,
      };
    }
  }, [dataSoure, selected, config]);

  const iconStyle = { fontSize: 15, marginRight: 5 }


  {/** children是移动端的 */}
  return children ? (
    children(sortList, handleClick)
  ) : (
    <div className={`content-head ${config.sectionDisplayPosition === 'left' ? 'leftcontentmain' : ''} ${config.sectionDisplayPosition === 'right' ? 'rightcontentmain' : ''}`}>
      <div className="left">
        {config.checkbox && (
          <Checkbox
            checked={isAllChecked}
            indeterminate={indeterminate}
            onChange={(e: CheckboxChangeEvent) => checkedDataArray(e)}
          >
          </Checkbox>
        )}
        {!!params.Mark && !params.searchText && (
          <>
            {imgDisplay && showImgSearch && <img
              onClick={(e) => {
                $visible(true);
                e.stopPropagation();
              }}
              className="_markImg"
              src={`/imageSearch/GetStream?mark=${params.Mark}&token=${inbiz.userInfo.token}`}
              onError={() => {
                $imgDisplay(false)
              }}
            />}
            <InbizImageSearchScreenshot
              visible={visible}
              imgUrl={`/imageSearch/GetStream?mark=${params.Mark}&token=${inbiz.userInfo.token}`}
              token={inbiz.userInfo.token}
              uploadUrl={'/ImageSearch/Upload'}
              onOk={(data: { nResult: number; mark: string }) => {
                if (data?.nResult === 0) {
                  const IndexName =
                    config.IndexCode === '_document_' ? '_document_' : config.IndexName;
                  inbiz(config.controlId).load({
                    IndexName: [IndexName],
                    documentType: config.IndexCode === '_document_' || config.IndexCode === 'file' ? 'file' : undefined,
                    ImgMarkId: data.mark,
                  });
                  $visible(false);
                }
              }}
              style={{ width: 455, left: 60, top: 100 }}
              onCancel={() => $visible(false)}
              themeColor={'var(--inbiz-color-primary)'}
              close
            />
          </>
        )}
        {total !== undefined && selected.length == 0 && (
          <span style={{ marginRight: 10, color: '#666' }}>
            <TextWidget>SearchResultEngine.findAnAppointmentForYou</TextWidget>
            {/**此处的空格是有用的 */}
            <span className="number"> {total} </span>
            <TextWidget>SearchResultEngine.relatedResults</TextWidget>
          </span>
        )}

        {
          selected.length > 0 && <span style={{ marginRight: 10 }}>
            <TextWidget>SearchResultEngine.haveSelected</TextWidget>
            {/**此处的空格是有用的 */}
            <span className="number"> {selected.length} </span>
            <TextWidget>SearchResultEngine.nameItem</TextWidget>
          </span>
        }
        {/* 中間插槽 */}
        {CenterPlugin}
      </div>

      <div className="headerright">
        <div className='headerOperations'>
          <SortArea config={config} controlId={controlId} handleSortChange={onSortChange} params={params} categoryLevel={categoryLevel}/>
          {showStyle && (
            <Select
              onChange={onShowStyleClick}
              value={showStyle}
              dropdownMatchSelectWidth={false}
              showArrow={false}
              dropdownClassName='showStyleSelect'
            // open
            >
              <Option key='list' title={getMessage('SearchResultEnginePreview.list')}>
                <InbizIcon
                  type='icon-ic-select-bold'
                  className='checkIcon'
                  style={iconStyle}
                />
                <InbizIcon
                  type='icon-ic-list'
                  style={iconStyle}
                />
                <TextWidget>SearchResultEngine.list</TextWidget>
              </Option>
              <Option key='thumbnail' title={getMessage('SearchResultEnginePreview.thumbnail')}>
                <InbizIcon
                  type='icon-ic-select-bold'
                  className='checkIcon'
                  style={iconStyle}
                />
                <InbizIcon
                  type='icon-datubiao'
                  style={iconStyle}
                />
                <TextWidget>SearchResultEngine.thumbnail</TextWidget>
              </Option>
              <Option key='bigthumbnail' title={getMessage('SearchResultEnginePreview.bigthumbnail')}>
                <InbizIcon
                  type='icon-ic-select-bold'
                  className='checkIcon'
                  style={iconStyle}
                />
                <InbizIcon
                  type='icon-chaodatubiao'
                  style={iconStyle}
                />
                <TextWidget>SearchResultEngine.bigthumbnail</TextWidget>
              </Option>
            </Select>
          )}
          {config.section && config.sectionDisplayPosition == 'right' && <div
            className={`showRightPanel ${showRightPanel || !!filterNumber ? 'displayRightPanel' : ''}`}
            onClick={() => $showRightPanel((bool: boolean) => !bool)}
          >
            {config.showSectionIcon && <InbizIcon
              type='icon-shaixuan-sousuo'
            />}
            <TextWidget>SearchResultEngine.filters</TextWidget>
            {!!filterNumber && (config.showfilterNumber || config.showfilterNumber == undefined) && <span className='filterNumber'>{filterNumber}</span>}
          </div>}
        </div>
      </div>
    </div >
  );
}

export default ContentHead;
